import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

const request = axios.create({
  baseURL: '/', // 基本路由
  timeout: 5000, // 超时时间
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
request.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['Authorization'] = 'Bearer ' + getToken()
    }
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  response => {
    const res = response.data

    // if the custom code is not 20000, it is judged as an error.
    if (res.status !== 200) {
      Message({
        message: res.msg || 'Error',
        type: 'error',
        duration: 5 * 1000 // 消息持续时间
      })

      // 识别token过期，失效等响应码
      if (res.status === 10015 || res.status === 10016) {
        // to re-login
        MessageBox.confirm('您已注销，您可以取消留在此页面，或重新登录!', '确认注销', {
          confirmButtonText: 'Re-Login',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      return Promise.reject(new Error(res.msg || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // 在这打印方便调试
    Message({
      message: error.msg || 'Response Error',
      type: 'error',
      duration: 5 * 1000 // 消息持续时间
    })
    return Promise.reject(error)
  }
)

export default request
